﻿using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace QuestionsAnswers.UI.Models
{
    public class QuestionsAnswersContext : DbContext
    {
        public DbSet<User> Users { get; set; }
        public DbSet<Question> Questions { get; set; }
        public DbSet<Answer> Answers { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
            modelBuilder.Entity<Question>().HasMany(q => q.Answers).WithRequired(q => q.Question).HasForeignKey(a => a.QuestionId).WillCascadeOnDelete(true);


        }


    }

    //             public static void Main(String [] args)
    //         {
    //             Database.SetInitializer<SurveyContext>(new SurveyCometInit());
    //         }

    public class QuestionsAnswersInit : System.Data.Entity.DropCreateDatabaseIfModelChanges<QuestionsAnswersContext>
    {
        protected override void Seed(QuestionsAnswersContext context)
        {
            User user = new User { UserName = "Hello" };
            Question question = new Question
                                    {
                                        Text = "What color is George Washington's white horse?",
                                        User = user


                                    };
     
            List<Answer> answers = new List<Answer>
                                       {
                                           new Answer()
                                               {
                                                   User = user,
                                                   Question = question,
                                                   Text = "White"
                                               },

                                           new Answer
                                               {
                                                   User = user,
                                                   Question = question,
                                                   Text = "Black"
                                               }
                                       };

            context.Questions.Add(question);

           answers.ForEach(x=>context.Answers.Add(x));

            context.SaveChanges();
        }
    }
}